<template>
  <div class="material-report-container">
    <!-- 顶部筛选区 -->
    <div class="filter-container">
      <el-card shadow="hover" class="filter-card">
        <el-form :inline="true" :model="filterForm" label-width="70px">
          <!-- 第一行 -->
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="物料代码">
                <el-select multiple v-model="filterForm.skuID" placeholder="请选择物料信息" clearable
                  :style="{ width: '100%' }" remote :remote-method="searchSelectNccMaterial" filterable>
                  <el-option v-for="item in materialNameOptions" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="查询条件">
                <el-switch v-model="filterForm.modeCode" active-text="按编码" inactive-text="按名称" :active-value="1"
                  :inactive-value="0"></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物资类别">
                <el-select clearable multiple filterable v-model="filterForm.skuClassId" placeholder="请选择物资类别">
                  <el-option v-for="(item, index) in typeData" :key="index" :value="item.value" :label="item.label">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
           <el-col :span="6">
             <el-form-item label="仓库" class="filter-form-item">
               <el-select clearable multiple filterable v-model="filterForm.wareHouseID" placeholder="请选择仓库">
                 <el-option v-for="item in NccStockOptions" :key="item.value" :label="item.label" :value="item.value" />
               </el-select>
             </el-form-item>
           </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="周转天数">
                <div style="display: flex; gap: 8px; width: 100%;">
                  <el-input clearable v-model="filterForm.turnoverDdy" placeholder="请输入周转天数"
                    style="flex: 1;"></el-input>
                  <el-dropdown @command="handleCommand" trigger="click">
                    <span class="el-dropdown-link">
                      {{ btnTXT }}<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="0">全部</el-dropdown-item>
                      <el-dropdown-item command="1">等于</el-dropdown-item>
                      <el-dropdown-item command="2">不等于</el-dropdown-item>
                      <el-dropdown-item command="3">包含</el-dropdown-item>
                      <el-dropdown-item command="4">不包含</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 第二行 -->
              <el-form-item label="周转率">
                <div class="range-inputs">
                  <el-input clearable v-model="filterForm.turnoverRateMinVal" placeholder="最小值"></el-input>
                  <span class="separator">-</span>
                  <el-input clearable v-model="filterForm.turnoverRateMaxVal" placeholder="最大值"></el-input>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="使用率">
                <div class="range-inputs">
                  <el-input clearable v-model="filterForm.skuRateMinVal" placeholder="最小值"></el-input>
                  <span class="separator">-</span>
                  <el-input clearable v-model="filterForm.skuRateMaxVal" placeholder="最大值"></el-input>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- 第三行 -->
              <el-form-item label="批次管理">
                <el-switch v-model="filterForm.openBatchNo" active-text="启用" inactive-text="停用" :active-value="'1'"
                  :inactive-value="'0'"></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="批次号">
                <div style="display: flex; gap: 8px; width: 100%;">
                  <el-input clearable v-model="filterForm.batchNo" placeholder="请输入批次号" style="flex: 1;"></el-input>
                  <el-dropdown @command="handleCommandCode" trigger="click">
                    <span class="el-dropdown-link">
                      {{ btnCode }}<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="0">全部</el-dropdown-item>
                      <el-dropdown-item command="1">等于</el-dropdown-item>
                      <el-dropdown-item command="2">不等于</el-dropdown-item>
                      <el-dropdown-item command="3">包含</el-dropdown-item>
                      <el-dropdown-item command="4">不包含</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="日期范围">
                <el-date-picker v-model="filterForm.timeList" type="datetimerange" range-separator="~"
                  start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 操作按钮 -->
              <el-form-item>
                <div>
                  <el-button type="primary" icon="el-icon-search"  @click="fetchBasicData">查询</el-button>
                  <el-button type="primary" icon="el-icon-search" @click="getLeft">周转率</el-button>
                  <el-button type="primary" icon="el-icon-download" @click="exportExcel">导出excel</el-button>
                  <el-button type="danger" icon="el-icon-refresh" @click="resetFilter">重置</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <!-- 主内容区 -->
    <div class="main-content">
      <basic-statistics :data="basicData" :dataLeft="leftData" :loading="basicLoading"
        :date-range="filterForm.dateRange" />
    </div>
    <div class="pagination-container">
      <el-pagination background layout=" total,prev, pager, next, sizes,jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :current-page="filterForm.pageNum" :page-size="filterForm.pageSize"
        :page-sizes="[20, 50,100]" :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  // 引入下拉框方法组件
  import SearchSelect from "@/views/components/dropDown/searchSelect.js";
  import {
    getAllWarehouseList, //获取仓库下拉
    informationType, //获取物料类型
  } from "@/api/index/warehouse";
  import BasicStatistics from './components/BasicStatistics'
  import {
    wmsReportBasicStatistic, //获取统计数量
    getnccMaterial, //获取物料
    wmsReportTurnoverRate, //左侧折线
  } from '@/api/report/allNews'
  export default {
    name: 'MaterialReport',
    components: {
      BasicStatistics,
    },
    data() {
      return {
        btnCode: '全部',
        btnTXT: '全部',
        filterForm: {
          skuID: [], //商品
          skuClassId: [], //物料类别
          wareHouseID: [], //仓库
          openBatchNo: '0', //批次管理开关
          batchNo: '', //批号
          turnoverRateMinVal: '', //最小周转率
          turnoverRateMaxVal: '', //最大周转率
          turnoverDdy: '', //周转天数
          turnoverDayValue: 0, //0 大于等于1 小于
          skuRateMinVal: '', //使用率开始
          skuRateMaxVal: '', //使用率结束
          batchNoValue: 0, //0等于任意一个 1等于 2不等于 3包含 4不包含
          timeList: [this.getDefaultStartDate(), this.getDefaultEndDate()],
          pageNum: 1,
          pageSize: 20,
          modeCode: 0
        },
        // 数据加载状态
        basicLoading: false,
        // 数据
        basicData: [],
        NccStockOptions: [], //仓库下拉
        typeData: [], //下拉选择物料类型
        total: 0,
        materialNameOptions: [], //查询物料名称
        leftData: [], //折线图
      }
    },
    created() {
      this.fetchBasicData();
      this.getType();
      this.getLeft();
    },
    mounted(){
      this.searchNCCStockList();
    },
    methods: {
      //导出excel
      exportExcel(){
        const [beginDate, endDate] = Array.isArray(this.filterForm.timeList) &&
          this.filterForm.timeList.length === 2 ?
          this.filterForm.timeList : [null, null];

        // 构建请求参数
        const params = {
          skuID: this.filterForm.skuID.join(','), //商品
          skuClassId: this.filterForm.skuClassId.join(','), //物料类别
          wareHouseID: this.filterForm.wareHouseID.join(','), //仓库
          openBatchNo: this.filterForm.openBatchNo, //批次管理开关
          batchNo: this.filterForm.batchNo, //批号
          turnoverRateMinVal: this.filterForm.turnoverRateMinVal, //最小周转率
          turnoverRateMaxVal: this.filterForm.turnoverRateMaxVal, //最大周转率
          turnoverDdy: this.filterForm.turnoverDdy, //周转天数
          turnoverDayValue: this.filterForm.turnoverDayValue, //0 大于等于1 小于
          skuRateMinVal: this.filterForm.skuRateMinVal, //使用率开始
          skuRateMaxVal: this.filterForm.skuRateMaxVal, //使用率结束
          batchNoValue: this.filterForm.batchNoValue, //0等于任意一个 1等于 2不等于 3包含 4不包含
          modeCode: this.filterForm.modeCode,
          beginDate, // 明确的开始日期
          endDate, // 明确的结束日期
          pageNum: this.filterForm.pageNum,
          pageSize: this.filterForm.pageSize,
        };
        this.download('stoUnit/exportReportBasicStatistic', {
          ...params
        }, `基础报表.xlsx`)
      },
      // 1、获取NCC仓库信息
      searchNCCStockList() {
        this.loading = true;
        SearchSelect.searchNCCStockList(this)
          .then(() => {
            // 获取到仓库信息后，更新 NccStockOptions
            this.NccStockOptions = this.NccStockList.map((item) => ({
              label: item.label,
              value: item.value,
            }));
          })
          .finally(() => {
            this.loading = false;
          });
      },
      // 远程搜索函数 获取NCC物料信息
      searchSelectNccMaterial(query) {
        if (query !== '') {
          const params = {
            materialName: query, // 传入输入的关键字
            modeCode: this.filterForm.modeCode, // 传入输入的关键字
          };
          // 调用接口进行物料信息查询
          getnccMaterial(params)
            .then(response => {
              if (response.code === 200) {
                // 更新物料选项
                this.materialNameOptions = response.data
              } else {
                this.materialNameOptions = [];
              }
            })
            .catch(error => {
              console.error('查询物料信息失败:', error);
              this.materialNameOptions = [];
            })
            .finally(() => {});
        } else {
          this.materialNameOptions = [];
        }
      },
      //分页
      handleSizeChange(val) {
        this.filterForm.pageSize = val;
        this.filterForm.pageNum = 1;
        this.fetchBasicData();
      },
      getLeft() {
        // 从timeList中提取开始和结束日期
        const [beginDate, endDate] = Array.isArray(this.filterForm.timeList) &&
          this.filterForm.timeList.length === 2 ?
          this.filterForm.timeList : [null, null];

        // 构建请求参数
        const params = {
          skuID: this.filterForm.skuID.join(','), //商品
          skuClassId: this.filterForm.skuClassId.join(','), //物料类别
          wareHouseID: this.filterForm.wareHouseID.join(','), //仓库
          openBatchNo: this.filterForm.openBatchNo, //批次管理开关
          batchNo: this.filterForm.batchNo, //批号
          turnoverRateMinVal: this.filterForm.turnoverRateMinVal, //最小周转率
          turnoverRateMaxVal: this.filterForm.turnoverRateMaxVal, //最大周转率
          turnoverDdy: this.filterForm.turnoverDdy, //周转天数
          turnoverDayValue: this.filterForm.turnoverDayValue, //0 大于等于1 小于
          skuRateMinVal: this.filterForm.skuRateMinVal, //使用率开始
          skuRateMaxVal: this.filterForm.skuRateMaxVal, //使用率结束
          batchNoValue: this.filterForm.batchNoValue, //0等于任意一个 1等于 2不等于 3包含 4不包含
          modeCode: this.filterForm.modeCode,
          beginDate, // 明确的开始日期
          endDate, // 明确的结束日期
        };
        wmsReportTurnoverRate(params).then(res => {
          this.leftData = this.processData(res.data);
        })
      },
      processData(rawData) {
        const result = [];
        const dateSeries = []; // 存储所有日期

        // 首先收集所有日期
        const dates = Object.keys(rawData).sort();
        dateSeries.push(...dates);

        // 创建一个物料映射，key为物料ID
        const materialMap = new Map();

        // 遍历每个日期的数据
        dates.forEach(date => {
          const items = rawData[date];

          items.forEach(item => {
            const materialKey = item.pk_material;

            // 如果物料不存在于map中，初始化
            if (!materialMap.has(materialKey)) {
              materialMap.set(materialKey, {
                pk_material: materialKey,
                skuName: item.Sku_Name,
                skuCode: item.Sku_Code,
                velocities: [], // 按日期顺序存储Velocity
                dates: dates, // 复制日期序列
              });
            }
            // 获取物料数据并添加当前日期的Velocity
            const materialData = materialMap.get(materialKey);
            materialData.velocities.push(item.Velocity);
          });
        });

        // 将Map转换为数组
        materialMap.forEach(value => {
          result.push({
            name: `${value.skuName} (${value.skuCode})`,
            skuName: value.skuName,
            pk_material: value.pk_material,
            velocities: value.velocities,
            dates: dates,
          });
        });

        return result;
      },
      handleCurrentChange(val) {
        this.filterForm.pageNum = val;
        this.fetchBasicData();
      },
      //获取存放商品类型
      getType() {
        informationType().then(res => {
          this.typeData = res.data;
        })
      },
      //获取日期
      getDefaultStartDate() {
        const date = new Date()
        date.setMonth(date.getMonth() - 1)
        return this.formatDate(date)
      },
      getDefaultEndDate() {
        return this.formatDate(new Date())
      },
      //格式化日期
      formatDate(date) {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
      },
      //下拉菜单
      handleCommand(command) {
        if (command == 0) {
          this.filterForm.turnoverDayValue = command;
          this.btnTXT = '大于等于';
          this.fetchBasicData();
        } else if (command == 1) {
          this.filterForm.turnoverDayValue = command;
          this.btnTXT = '小于';
          this.fetchBasicData();
        }
      },
      handleCommandCode(command) {
        if (command == 0) {
          this.filterForm.batchNoValue = command;
          this.btnCode = '全部';
          this.fetchBasicData();
        } else if (command == 1) {
          this.filterForm.batchNoValue = command;
          this.btnCode = '等于';
          this.fetchBasicData();
        } else if (command == 2) {
          this.filterForm.batchNoValue = command;
          this.btnCode = '不等于';
          this.fetchBasicData();
        } else if (command == 3) {
          this.filterForm.batchNoValue = command;
          this.btnCode = '包含';
          this.fetchBasicData();
        } else {
          this.filterForm.batchNoValue = command;
          this.btnCode = '不包含';
          this.fetchBasicData();
        }
      },
      resetFilter() {
        this.filterForm = {
          skuID: [],
          skuClassId: [],
          wareHouseID: [],
          openBatchNo: '0',
          batchNo: '',
          turnoverRateMinVal: '',
          turnoverRateMaxVal: '',
          turnoverDdy: '',
          turnoverDayValue: 0,
          skuRateMinVal: '',
          skuRateMaxVal: '',
          batchNoValue: 0,
          timeList: [this.getDefaultStartDate(), this.getDefaultEndDate()],
          pageNum: 1,
          pageSize: 20,
        }
        this.fetchBasicData()
      },
      async fetchBasicData() {
        this.basicLoading = true;
        try {
          // 从timeList中提取开始和结束日期
          const [beginDate, endDate] = Array.isArray(this.filterForm.timeList) &&
            this.filterForm.timeList.length === 2 ?
            this.filterForm.timeList : [null, null];

          // 构建请求参数
          const params = {
            skuID: this.filterForm.skuID.join(','), //商品
            skuClassId: this.filterForm.skuClassId.join(','), //物料类别
            wareHouseID: this.filterForm.wareHouseID.join(','), //仓库
            openBatchNo: this.filterForm.openBatchNo, //批次管理开关
            batchNo: this.filterForm.batchNo, //批号
            turnoverRateMinVal: this.filterForm.turnoverRateMinVal, //最小周转率
            turnoverRateMaxVal: this.filterForm.turnoverRateMaxVal, //最大周转率
            turnoverDdy: this.filterForm.turnoverDdy, //周转天数
            turnoverDayValue: this.filterForm.turnoverDayValue, //0 大于等于1 小于
            skuRateMinVal: this.filterForm.skuRateMinVal, //使用率开始
            skuRateMaxVal: this.filterForm.skuRateMaxVal, //使用率结束
            batchNoValue: this.filterForm.batchNoValue, //0等于任意一个 1等于 2不等于 3包含 4不包含
            modeCode: this.filterForm.modeCode,
            beginDate, // 明确的开始日期
            endDate, // 明确的结束日期
            pageNum: this.filterForm.pageNum,
            pageSize: this.filterForm.pageSize,
          };
          // 移除不需要的timeList参数
          wmsReportBasicStatistic(params).then(res => {
            this.basicData = res.data.rows;
            this.total = res.data.total;
          });
        } catch (error) {
          console.error('获取基础统计数据失败:', error);
          this.$message.error('获取数据失败');
        } finally {
          this.basicLoading = false;
        }
      },
    }
  }
</script>

<style scoped lang="scss">
  .material-report-container {
    padding: 16px;
    background-color: #f5f7fa;
  }

  .filter-container {
    margin-bottom: 16px;
  }

  .filter-card {
    border-radius: 4px;
  }


  .range-inputs {
    display: flex;

    ::v-deep .el-input--medium .el-input__inner {
      width: 135px;
    }
  }


  .range-inputs .separator {
    color: #909399;
    font-size: 14px;
  }

  .action-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 8px;
  }

  .main-content {
    background: #fff;
    padding: 16px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }

  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    display: flex;
    align-items: center;
  }

  .el-dropdown-link i {
    margin-left: 4px;
  }

  .el-form-item__label {
    padding-right: 8px;
  }

  .main-content {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
</style>
